<template>
	<div class="front bj">
        <el-scrollbar style="height: 100%;">
    		<el-form label-width="95px" label-position="left" :model="formData" ref="formRef" :rules="formRules">
                <el-form-item label="名称：" prop="name">
                    <el-input v-model.trim="formData.name" @keyup.enter.native="enterKey($event, 'MA1')"></el-input>
                </el-form-item>
                <el-form-item label="汇率：" prop="exchangeRate" >
                    <el-input v-model.trim="formData.exchangeRate" ref="MA1" @keyup.enter.native="enterKey($event, 'MA2')" @blur="changeRate"></el-input>
                </el-form-item>
                <el-form-item label="折算方式：" prop="convertType">
                    <el-select v-model="formData.convertType" ref="MA2" @keyup.enter.native="enterKey($event, 'MA3')" placeholder="选择折算方式" style="width: 100%;">
                        <el-option label="原币*汇率=本位币" value="1"></el-option>
                        <el-option label="原币/汇率=本位币" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="小数位：" prop="decimals">
                    <el-input v-model.trim="formData.decimals" ref="MA3" @keyup.enter.native="enterKey($event, 'MA4')"></el-input>
                </el-form-item>
                <el-form-item label="汇率类别：" prop="fixedExchangeRate">
                    <el-select v-model="formData.fixedExchangeRate" ref="MA4" placeholder="选择汇率类别" style="width: 100%;">
                        <el-option label="固定汇率" value="1"></el-option>
                        <el-option label="浮动汇率" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="连续增加：" style="margin-bottom: 10px !important;margin-top: -10px !important" v-if="!rowId">
                    <el-checkbox v-model="continueAdd"></el-checkbox>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" @click="save('formRef')">保存</el-button>
                    <el-button type="danger" size="small" @click="close">关闭</el-button>
                </el-form-item>
            </el-form>
        </el-scrollbar>
	</div>
</template>
<script>
export default {
	data() {
		let validateIsNum = (rule, value, callback) => {        //验证是否是一个数字
            if(!/^[0-9]+.?[0-9]*$/.test(value)) {
                return callback(new Error('只能输入数字！'));
            }
            callback();
        }
		return {
			continueAdd: false,
			rowId: this.$store.state.currencyTypeStore.rowId,
			formData: {
				name: '',
                exchangeRate: '',
                convertType: '',
                decimals: '',
                fixedExchangeRate: ''
			},
			formRules: {
				name: [{required: true, message: '输入名称', triggle: 'blur'}],
                exchangeRate: [{required: true, message: '输入汇率', triggle: 'blur'}],
                convertType: [{required: true, message: '选择折算方式', triggle: 'change'}],
                decimals: [{required: true, message: '输入小位数', triggle: 'blur'}, {validator: validateIsNum, trigger: 'blur'}],
                fixedExchangeRate: [{required: true, message: '选择汇率类别', trigger: 'change'}],
			},
            options: this.$store.state.options
		}
	},
	watch:{
        "formData.decimals"(newVal){
            if(newVal){
                if(this.formData['exchangeRate']){
                    this.formData['exchangeRate'] = parseFloat(this.formData['exchangeRate']).toFixed(newVal)
                }
            }
        },
    },
	methods: {
		getUpdateData() {
			this.$http.get('currency/findCurrencyById?id=' + this.rowId).then(res => {
                if(res.data.code == 20001) {
                    if(res.data.data) {
                        res.data.data['state'] = Boolean(res.data.data['state']);
                        res.data.data['decimals'] = res.data.data['decimals'].toString();
                        res.data.data['convertType'] = res.data.data['convertType'] == 1 ? '原币*汇率=本位币' : '原币/汇率=本位币';
                        res.data.data['fixedExchangeRate'] = res.data.data['fixedExchangeRate'] == 1 ? '固定汇率' : '浮动汇率';
                        this.formData = res.data.data;
                    }
                }
            });
		},
		save(formName) {
            this.$refs[formName].validate((valid) => {
            	if(this.formData['id']) {			//修改
            		let data = {
                        id: this.formData['id'],
                        name: this.formData['name'],
                        exchangeRate: this.formData['exchangeRate'],
                        convertType: this.formData['convertType'] == '原币*汇率=本位币' || (this.formData['convertType'] == 1) ? 1 : 0,
                        decimals: this.formData['decimals'],
                        fixedExchangeRate: this.formData['fixedExchangeRate'] == '固定汇率' || (this.formData['fixedExchangeRate'] == 1) ? 1 : 0
                    }
                    this.$http({
                        method: "post",
                        url: "currency/updateCurrency",
                        params: data,
                        dataType: 'json'
                    }).then(res => {
                        if(res.data.code == 20001) {
                            this.$message({message: '修改成功', type: 'success', duration: 1500});
                            setTimeout(() => {
                                this.close();
                                this.$store.dispatch('currencyTypeStore/getTableData');
                            }, 1000);
                        }
                    });
            	} else {			//新增
            		let data = {
	                    name: this.formData['name'],
	                    exchangeRate: this.formData['exchangeRate'],
	                    convertType: this.formData['convertType'],
	                    decimals: this.formData['decimals'],
	                    fixedExchangeRate: this.formData['fixedExchangeRate']
	                }
            		if (valid) {
	                    this.$http({
	                        method: "post",
	                        url: "currency/insertCurrency",
	                        params: data
	                    }).then(res => {
	                        if(res.data.code === 20001) {
	                            this.$message({message: '添加成功', type: 'success'});
	                            setTimeout(() => {
	                                this.continueAdd ? this.$refs[formName].resetFields() : this.close();
	                                this.$store.dispatch('currencyTypeStore/getTableData');
	                            }, 1000);
	                        } else {
	                            this.$message.error(res.data.msg || '新增失败');
	                        }
	                    });
	                }
            	}
            });
        },
        changeRate(){               //汇率失去焦点
            if(this.formData['decimals']){
                this.formData['exchangeRate'] = parseFloat(this.formData['exchangeRate']).toFixed(this.formData['decimals'])
            }
        },
		close() {           //关闭新增弹窗
            let index = parent.layer.getFrameIndex(window.name);    //先得到当前iframe层的索引
            parent.layer.close(index);
        },
        enterKey(lastRef, nextRef) {		//回车键换行
            if(lastRef.target.value) {
                this.$refs[nextRef].focus();
            }
        }
	},
	created() {
		if(this.rowId) {
			this.getUpdateData();
		}
	}
}
</script>